<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Validation\Rule;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;

class CategoryController extends Controller
{
    /**
     * 分类列表，支持分页和搜索
     * @param \Illuminate\Http\Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'per_page' => 'integer|min:1|max:100',
            'page' => 'integer|min:1',
            'search' => 'nullable|string|max:255'
        ], [
            'per_page.integer' => '每页数量必须为整数',
            'per_page.min' => '每页数量至少为1',
            'per_page.max' => '每页数量最多为100',
            'page.integer' => '页码必须为整数',
            'page.min' => '页码至少为1',
            'search.max' => '搜索关键词不能超过255个字符',
        ]);

        $perPage = $validated['per_page'] ?? 10;
        $page = $validated['page'] ?? 1;
        $search = $validated['search'] ?? null;

        $query = Category::orderBy('created_at', 'desc');
        
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                ->orWhere('slug', 'like', "%{$search}%");
            });
        }

        $categories = $query->paginate($perPage, ['*'], 'page', $page);

        return response()->json($categories, 200);
    }

    /**
     * 前台展示：获取最新10条分类数据
     * @return JsonResponse
     */
    public function latest(): JsonResponse
    {
        $categories = Category::select('id', 'name', 'slug')
            ->orderBy('created_at', 'desc')
            ->take(10)
            ->get();

        return response()->json([
            'data' => $categories,
            'message' => '成功获取最新分类'
        ], 200);
    }

    /**
     * 新增分类
     * @param \Illuminate\Http\Request $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50|unique:categories,name',
            'description' => 'nullable|string',
        ], [
            'name.required' => '分类名称不能为空',
            'name.max' => '分类名称不能超过50个字符',
            'name.unique' => '分类名称已存在',
            'description.string' => '描述必须为字符串',
        ]);

        $category = Category::create($validated);

        return response()->json([
            'data' => $category,
            'message' => '创建分类成功',
        ], 201);
    }

    /**
     * 更新分类
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\Category $category
     * @return JsonResponse
     */
    public function update(Request $request, Category $category): JsonResponse
    {
        $validated = $request->validate([
            'name' => [
                'required',
                'string',
                'max:50',
                Rule::unique('categories', 'name')->ignore($category->id),
            ],
            'description' => 'nullable|string',
        ], [
            'name.required' => '分类名称不能为空',
            'name.max' => '分类名称不能超过50个字符',
            'name.unique' => '分类名称已存在',
            'description.string' => '描述必须为字符串',
        ]);

        $category->update($validated);

        return response()->json([
            'data' => $category,
            'message' => '更新分类成功',
        ], 200);
    }

    /**
     * 删除分类
     * @param \app\Models\Category $category
     * @return JsonResponse
     */
    public function destroy(Category $category): JsonResponse
    {
        try {
            $category->delete();
            return response()->json(null, 204);
        } catch (QueryException $e) {
            if ($e->getCode() === '23000') {
                return response()->json([
                    'message' => '该分类下存在文章，无法删除。'
                ], 409);
            }
            return response()->json([
                'message' => '删除分类失败',
            ], 500);
        }
    }
}
